<template>
  <div class="video-upload">
    <h2>视频上传（自动 Faststart 优化）</h2>

    <div class="upload-area">
      <input
        ref="fileInput"
        type="file"
        accept="video/mp4"
        @change="handleFileSelect"
        :disabled="uploading"
      >
      <button @click="$refs.fileInput.click()" :disabled="uploading">
        选择视频文件
      </button>
    </div>

    <div v-if="selectedFile" class="file-info">
      <p><strong>文件:</strong> {{ selectedFile.name }}</p>
      <p><strong>大小:</strong> {{ formatSize(selectedFile.size) }}</p>
    </div>

    <div v-if="uploading" class="progress-section">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: progress + '%' }"></div>
      </div>
      <p class="status-text">{{ statusText }}</p>
      <p class="progress-text">{{ progress }}%</p>
    </div>

    <div v-if="uploadResult" class="result-section">
      <h3>✓ 上传成功</h3>
      <p><strong>URL:</strong> <a :href="uploadResult.url" target="_blank">{{ uploadResult.url }}</a></p>
      <p v-if="optimized"><strong>状态:</strong> ✓ 已优化为 Faststart 格式</p>
      <p v-else><strong>状态:</strong> ⚠️ 优化中或超时（文件可用）</p>
      
      <video v-if="optimized" :src="uploadResult.url" controls style="max-width: 100%; margin-top: 20px;"></video>
    </div>

    <div v-if="error" class="error-section">
      <p>{{ error }}</p>
    </div>
  </div>
</template>

<script>
import { uploadVideoWithOptimization } from '../utils/ossUpload'

export default {
  name: 'VideoUpload',
  data() {
    return {
      selectedFile: null,
      uploading: false,
      progress: 0,
      statusText: '',
      uploadResult: null,
      optimized: false,
      error: null
    }
  },

  methods: {
    handleFileSelect(event) {
      const file = event.target.files[0]
      if (!file) return

      if (!file.type.includes('mp4')) {
        this.error = '请选择 MP4 格式的视频文件'
        return
      }

      this.selectedFile = file
      this.error = null
      this.uploadResult = null
      this.optimized = false
    },

    async uploadVideo() {
      if (!this.selectedFile) return

      this.uploading = true
      this.progress = 0
      this.error = null

      try {
        const result = await uploadVideoWithOptimization(this.selectedFile, {
          onProgress: (percent, stage) => {
            this.progress = percent
            
            if (stage === 'uploading') {
              this.statusText = '正在上传...'
            } else if (stage === 'optimizing') {
              this.statusText = '正在优化为 Faststart 格式...'
            }
          },
          
          onOptimizationStart: () => {
            this.statusText = '上传完成，开始优化...'
          },
          
          onOptimizationComplete: (success) => {
            this.optimized = success
            if (success) {
              this.statusText = '优化完成！'
            } else {
              this.statusText = '优化超时，但文件已可用'
            }
          },
          
          waitForOptimization: true,
          maxWaitTime: 300000 // 5 分钟
        })

        this.uploadResult = result
        this.progress = 100

      } catch (err) {
        console.error('上传失败:', err)
        this.error = `上传失败: ${err.message}`
      } finally {
        this.uploading = false
      }
    },

    formatSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
  },

  watch: {
    selectedFile(newFile) {
      if (newFile) {
        this.uploadVideo()
      }
    }
  }
}
</script>

<style scoped>
.video-upload {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.upload-area {
  text-align: center;
  padding: 40px;
  border: 2px dashed #ccc;
  border-radius: 8px;
  margin-bottom: 20px;
}

.upload-area input[type="file"] {
  display: none;
}

.upload-area button {
  background: #409eff;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.upload-area button:hover:not(:disabled) {
  background: #66b1ff;
}

.upload-area button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.file-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.progress-section {
  margin-bottom: 20px;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background: #eee;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff, #67c23a);
  transition: width 0.3s;
}

.status-text {
  text-align: center;
  color: #606266;
  font-weight: 500;
}

.progress-text {
  text-align: center;
  color: #909399;
}

.result-section {
  background: #f0f9ff;
  border: 1px solid #409eff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.result-section h3 {
  color: #67c23a;
  margin-top: 0;
}

.result-section a {
  color: #409eff;
  word-break: break-all;
}

.error-section {
  background: #fef0f0;
  border: 1px solid #f56c6c;
  border-radius: 4px;
  padding: 15px;
  color: #f56c6c;
}
</style>
